<template>
  <div class="order-list-page">
    <div class="order-list-container">
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <h1>我的订单</h1>
      </div>
      
      <!-- 订单状态筛选 -->
      <div class="order-tabs">
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'all' }"
          @click="switchTab('all')"
        >
          全部
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'pending' }"
          @click="switchTab('pending')"
        >
          待支付
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'paid' }"
          @click="switchTab('paid')"
        >
          已支付
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'completed' }"
          @click="switchTab('completed')"
        >
          已完成
        </div>
      </div>
      
      <!-- 加载中状态 -->
      <van-loading v-if="loading" type="spinner" color="#1989fa" class="loading" />
      
      <!-- 空订单提示 -->
      <div v-else-if="filteredOrders.length === 0" class="empty-orders">
        <van-icon name="orders-o" size="60" color="#c0c4cc" />
        <p>暂无订单</p>
      </div>
      
      <!-- 订单列表 -->
      <div v-else class="order-items">
        <!-- 加载更多提示 -->
        <div v-if="loading && orders.length > 0" class="loading-more">
          <van-loading type="spinner" color="#1989fa" size="20px" />
          <span>加载中...</span>
        </div>
        <div 
          v-for="order in filteredOrders" 
          :key="order.id" 
          class="order-item"
          @click="viewOrderDetail(order.id)"
        >
          <!-- 订单头部 -->
          <div class="order-header">
            <span class="shop-name">{{ order.shop?.shop_name || order.shop_name || '未知店铺' }}</span>
            <span class="order-status" :class="getStatusClass(order.status)">
              {{ getStatusText(order) }}
            </span>
          </div>
          
          <!-- 订单商品信息 -->
          <div class="order-product">
            <img :src="order.item?.image || order.item_image || 'https://via.placeholder.com/300x300?text=商品'" alt="酒品图片" class="product-image" />
            <div class="product-info">
              <h4>{{ order.item?.name || order.item_name || '未知商品' }}</h4>
              <p class="product-desc">{{ order.item?.info || '' }}</p>
              <div class="product-price-quantity">
                <span class="price">¥{{ order.price || 0 }}/ml</span>
                <span class="quantity">x{{ order.num || 0 }}ml</span>
              </div>
            </div>
          </div>
          
          <!-- 订单底部 -->
          <div class="order-footer">
            <div class="order-time">{{ formatDateTime(order.create_time * 1000) }}</div>
            <div class="order-total">
              总计: <span class="total-price">¥{{ order.total }}</span>
            </div>
          </div>
          
          <!-- 订单操作按钮 -->
          <div class="order-actions">
            <van-button 
              v-if="order.status === 0" 
              type="primary" 
              size="small" 
              class="action-btn pay-btn"
              @click.stop="payOrder(order.id)"
            >
              立即支付
            </van-button>
            <van-button 
              v-if="order.status === 0" 
              type="default" 
              size="small" 
              class="action-btn cancel-btn"
              @click.stop="cancelOrder(order.id)"
            >
              取消订单
            </van-button>
            <van-button 
              v-if="order.status === 1" 
              type="primary" 
              size="small" 
              class="action-btn detail-btn"
              @click.stop="viewOrderDetail(order.id)"
            >
              查看详情
            </van-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { api, mockData } from '../api'

export default {
  name: 'OrderList',
  data() {
    return {
      loading: false,
      activeTab: 'all',
      orders: [],
      page: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    }
  },
  computed: {
    // 根据选中的标签筛选订单
    filteredOrders() {
      if (this.activeTab === 'all') {
        return this.orders
      } else if (this.activeTab === 'pending') {
        return this.orders.filter(order => order.status === 0)
      } else if (this.activeTab === 'paid') {
        return this.orders.filter(order => order.status === 1)
      } else if (this.activeTab === 'completed') {
        return this.orders.filter(order => order.status === 8)
      }
      return this.orders
    }
  },
  mounted() {
    this.loadOrders()
    // 添加滚动事件监听
    window.addEventListener('scroll', this.handleScroll)
  },
  
  beforeDestroy() {
    // 移除滚动事件监听
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 返回上一页
    goBack() {
      // this.$router.back()
      this.$router.push("/")
    },
    
    // 切换标签
    switchTab(tab) {
      this.activeTab = tab
      this.loadOrders(false) // 切换标签时重新加载第一页
    },
    
    // 加载更多订单
    loadMore() {
      if (!this.loading && this.hasMore) {
        this.loadOrders(true)
      }
    },
    
    // 处理滚动事件，实现自动加载
    handleScroll() {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
      const clientHeight = document.documentElement.clientHeight || window.innerHeight
      
      // 当滚动到底部100px时触发加载更多
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        this.loadMore()
      }
    },
    
    // 加载订单列表
    async loadOrders(isLoadMore = false) {
      try {
        if (!isLoadMore) {
          this.loading = true
          this.page = 1
          this.hasMore = true
        } else if (!this.hasMore) {
          return
        }
        
        // 构建请求参数
        let status = ''
        if (this.activeTab === 'pending') status = '0'
        else if (this.activeTab === 'paid') status = '1'
        else if (this.activeTab === 'completed') status = '8' // 完成状态对应8
        
        const params = {
          page: this.page,
          page_size: this.pageSize
        }
        
        // 只有当不是查询全部订单时才传递status参数
        if (status) {
          params.status = status
        }
        
        // 尝试调用真实API获取订单列表
        let response
        try {
          response = await api.myOrders(params)
        } catch (apiError) {
          // console.log('API调用失败，使用mock数据:', apiError)
          // // 使用mock数据作为降级方案
          // response = mockData.orderList
          
          // // 模拟分页效果
          // if (isLoadMore) {
          //   // 模拟第二页数据
          //   const secondPageData = JSON.parse(JSON.stringify(response))
          //   secondPageData.data.list = secondPageData.data.list.map(order => ({
          //     ...order,
          //     id: order.id + 10
          //   }))
          //   response = secondPageData
          // }
        }
        
        // 更新订单数据
        if (isLoadMore) {
          this.orders = [...this.orders, ...response.data.list]
        } else {
          this.orders = response.data.list
        }
        
        // 更新分页信息
        this.total = response.data.total
        this.pageSize = response.data.page_size
        this.hasMore = this.orders.length < this.total
        
        // 如果还有更多数据，准备下一页
        if (this.hasMore) {
          this.page++
        }
        
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$toast('获取订单列表失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    // 格式化日期时间
    formatDateTime(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case 0:
          return 'status-pending'
        case 1:
          return 'status-paid'
        case 2:
          return 'status-waiting-pour'
        case 3:
          return 'status-pouring'
        case 4:
          return 'status-paused'
        case 5:
          return 'status-stopped'
        case 6:
          return 'status-partial-refund'
        case 7:
          return 'status-full-refund'
        case 8:
          return 'status-completed'
        default:
          return ''
      }
    },
    
    // 根据状态获取显示文本（兼容接口返回）
    getStatusText(order) {
      return order.status_text || {
        0: '待支付',
        1: '已支付',
        2: '待打酒',
        3: '出酒中',
        4: '暂停',
        5: '未完成停止',
        6: '部分退款',
        7: '全部退款',
        8: '完成'
      }[order.status] || '未知状态';
    },
    
    // 查看订单详情
    viewOrderDetail(orderId) {
      this.$router.push(`/order-detail/${orderId}`)
    },
    
    // 支付订单
    payOrder(orderId) {
      // 模拟支付流程
      this.$toast.loading({ message: '支付中...', duration: 0 })
      
      setTimeout(() => {
        this.$toast.clear()
        this.$toast.success('支付成功')
        
        // 更新订单状态
        const order = this.orders.find(o => o.id === orderId)
        if (order) {
          order.status = 1
          order.status_text = '已支付'
        }
      }, 1500)
    },
    
    // 取消订单
    cancelOrder(orderId) {
      this.$dialog.confirm({
        title: '确认取消',
        message: '您确定要取消该订单吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 更新订单状态
        const order = this.orders.find(o => o.id === orderId)
        if (order) {
          order.status = 3
          order.status_text = '已取消'
        }
        this.$toast.success('订单已取消')
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</script>

<style scoped>
.order-list-page {
  height: 100vh;
  background-color: #f8f8f8;
}

.order-list-container {
  width: 100%;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-icon {
  font-size: 20px;
  margin-right: 20px;
}

.header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.order-tabs {
  display: flex;
  background-color: #fff;
  margin-bottom: 10px;
  position: sticky;
  top: 51px;
  z-index: 10;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  font-size: 14px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #1989fa;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 3px;
  background-color: #1989fa;
  border-radius: 3px;
}

.loading {
  padding: 50px 0;
  text-align: center;
}

.empty-orders {
  text-align: center;
  padding: 50px 0;
  color: #999;
}

.empty-orders p {
  margin-top: 10px;
  font-size: 14px;
}

.order-items {
  padding: 10px;
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}

.loading-more span {
  margin-left: 8px;
}

.order-item {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.shop-name {
  font-size: 15px;
  font-weight: bold;
  color: #333;
}

.order-status {
  font-size: 13px;
  padding: 2px 8px;
  border-radius: 10px;
}

.status-pending {
  background-color: #e1f3d8;
  color: #67c23a;
}

.status-paid {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-waiting-pour {
  background-color: #fff7e6;
  color: #e6a23c;
}

.status-pouring {
  background-color: #f0f9ff;
  color: #36cfc9;
}

.status-paused {
  background-color: #f5f7fa;
  color: #909399;
}

.status-stopped {
  background-color: #fef0f0;
  color: #f56c6c;
}

.status-partial-refund {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-full-refund {
  background-color: #fef0f0;
  color: #f56c6c;
}

.status-completed {
  background-color: #f0f9eb;
  color: #67c23a;
}

.order-product {
  display: flex;
  margin-bottom: 15px;
}

.product-image {
  width: 70px;
  height: 70px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 15px;
}

.product-info {
  flex: 1;
}

.product-info h4 {
  margin: 0 0 5px 0;
  font-size: 15px;
  font-weight: bold;
  color: #333;
}

.product-desc {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 14px;
  font-weight: bold;
  color: #f56c6c;
}

.quantity {
  font-size: 13px;
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-total {
  font-size: 14px;
  color: #666;
}

.total-price {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.action-btn {
  padding: 5px 15px;
  font-size: 13px;
  border-radius: 15px;
}

.pay-btn {
  background-color: #1989fa;
  color: #fff;
}

.cancel-btn {
  border: 1px solid #dcdfe6;
  color: #606266;
}

.detail-btn {
  background-color: #1989fa;
  color: #fff;
}
</style>